package com.sunnada.edu.system.pub.common;

public class VideoUtils {
	
	private static String rootPath = AppContext.getInstance().getRootPath(); 
	
	//Mencoder 转avi 的命令行
	private static String aviCLI = rootPath + "mplayer\\mencoder.exe %inputFile% -o %outputFile% -of avi -oac mp3lame -lameopts aq=7:cbr:br=224 -srate 32000 -vf harddup -ofps 25 -ovc x264 -x264encopts bitrate=3000:level_idc=4.1";
	
	private static String aviLinux = "mencoder %inputFile% -o %outputFile% -of avi -oac mp3lame -lameopts aq=7:cbr:br=224 -srate 32000 -vf harddup -ofps 25 -ovc x264 -x264encopts bitrate=3000:level_idc=4.1";
	
	//Mencoder 转 flv 的命令行
	private static String flvCLI = rootPath + "mplayer\\mencoder.exe %inputFile% -o %outputFile% -of lavf  -lavfopts i_certify_that_my_video_stream_does_not_use_b_frames  -oac mp3lame -lameopts abr:br=16 -ovc lavc -lavcopts vcodec=flv:vbitrate=150:mbd=0:last_pred=0:dia=01:cmp=0 -vf scale=200:-3 -ofps 12 -srate 22050";

	//private static String flvLinux = "mencoder %inputFile% -o %outputFile% -quiet -oac mp3lame -lameopts abr:br=16 -srate 22050 -af channels=2 -ovc lavc -vf harddup,hqdn3d,scale=200:-3 -lavcopts vcodec=flv:vbitrate=150:mbd=0:trell:v4mv:turbo:keyint=45 -ofps 13 -of lavf";
	private static String flvLinux = "mencoder %inputFile% -o %outputFile% -of lavf -oac mp3lame -lameopts abr:br=16 -ovc lavc -lavcopts vcodec=flv:vbitrate=150:mbd=0:mv0:trell:v4mv:cbp:last_pred=3 -vf scale=200:-3 -ofps 12 -srate 22050";
	private static String wmvFlvLinux = "ffmpeg -i %inputFile% -y -ab 32 -ar 22050 -qscale 10 -s 248*153 -r 15 %outputFile%";
	
	private static String gifCLI = rootPath + "mplayer\\ffmpeg -i %inputFile% -vframes 15 -y -f gif -pix_fmt rgb24 %outputFile% ";
	
	private static String gifLinux = "ffmpeg -i %inputFile% -vframes 15 -y -f gif -pix_fmt rgb24 %outputFile% ";
	
	private static String jpgCLI = rootPath + "mplayer\\ffmpeg -i %inputFile% -y -f image2 -ss 1 -t 0.001 -s %width%*%height% %outputFile% ";
	
	private static String jpgLinux = "ffmpeg -i %inputFile% -y -f image2 -ss 1 -t 0.001 -s %width%*%height% %outputFile% ";
	  
	
	/* 视频转换为FLV格式 
	   * @param  -vf scale=512:-3：-vf表示视频格式，scale是缩放，512:-3表示强制将宽度设置为512，高度写为-3表示保持高宽比，也可以设置为-1或-2，具体表示什么，有兴趣的可以尝试一下。如果要强制转化为统一大小，可以直接写-vf scale=640:480，但笔者个人建议用-3来保持高宽比。-vf里还有expand和crop参数，例如：-vf scale=512:384,expand=512:384:::1,crop=512:384:0:0，expand表示膨胀，crop表示裁剪；

     -ofps 12：输出视频的帧频，一般，用于flash播放的视频帧频高了没有没有意义，反而会增加视频文件大小，但如果ofps设置的不合适，比如源视频帧频不是ofps的整数倍，可能会导致转换后的视频、音频不同步，似乎可以将这一参数改为-noskip来解决这一问题；    

    -srate 22050：音频采样率一般为22050或44100。

	   * @param vbitrate=500：指定视频比特率为500，这个参数很重要，vbitrate大了可以让视频品质增加，但会让文件变的很大（可以参考flash8自带的转换工具的参数：低品质为150kb/s，中等品质为400kb/s，高品质为700kb/s）。 
	   
	*/  
	
	public static void convertVideoToAvi(String sourceFile, String aviFile) {
		String newAviCLI = "";
		System.out.println(aviCLI);
		if(System.getProperty("os.name").indexOf("Windows")>-1){
			newAviCLI = replaceCLI(
					aviCLI, 
					new String[] {"inputFile", "outputFile"}, 
					new String[] {sourceFile, aviFile}
			);
		} else {
			newAviCLI = replaceCLI(
					aviLinux, 
					new String[] {"inputFile", "outputFile"}, 
					new String[] {sourceFile, aviFile}
			);
		}
		Process process = null;
		try {
			process = Runtime.getRuntime().exec(newAviCLI);
			
			new  StreamGobble(process.getInputStream(),  "INFO" ).start();   
		    new  StreamGobble(process.getErrorStream(),  "ERROR" ).start();   
		    int  status = process.waitFor();   
		    System.out.println("Process exitValue: "  + status);   
        } catch (Throwable t) {   
			t.printStackTrace();   
        } finally {   
	        if  (process ==  null )   
	            process.destroy();   
	        process = null ;   
	    } 
	}
	
	public static void convertVideoToFlv(String sourceFile, String flvFile) {
		String newFlvCLI = "";
		if(System.getProperty("os.name").indexOf("Windows")>-1){
			newFlvCLI = replaceCLI(
					flvCLI, 
					new String[] {"inputFile", "outputFile"}, 
					new String[] {sourceFile, flvFile}
			);
		} else {
			newFlvCLI = replaceCLI(
					flvLinux, 
					new String[] {"inputFile", "outputFile"}, 
					new String[] {sourceFile, flvFile}
			);
		}
		
		try {
			//Process process = Runtime.getRuntime().exec(newFlvCLI);
			Process process = null;
			try {
				process = Runtime.getRuntime().exec(newFlvCLI);
				
				new  StreamGobble(process.getInputStream(),  "INFO" ).start();   
			    new  StreamGobble(process.getErrorStream(),  "ERROR" ).start();   
			    int  status = process.waitFor();   
			    System.out.println("Process exitValue: "  + status);   
	        } catch (Throwable t) {   
				t.printStackTrace();   
	        } finally {   
		        if  (process ==  null )   
		            process.destroy();   
		        process = null ;   
		    } 
			///InputStream stderr = process.getErrorStream();   
            //InputStreamReader isr = new InputStreamReader(stderr);   
            //BufferedReader br = new BufferedReader(isr);   
          //  String line = "";   
            //System.out.println("<ERROR>");   
           // while (line != null){
           // 	try{
            ////	line = br.readLine();
            //	}catch(Exception e){
            //		e.printStackTrace();
            //	}
            //	System.out.println(line);   
           // }
                
           // System.out.println("</ERROR>");   
           // int exitVal = process.waitFor();   
            //System.out.println("Process exitValue: " + exitVal);   
        } catch (Throwable t) {   
			t.printStackTrace();   
        }   
	}	
	
	/**explain wmv专用
	 * @author niujs 2015-3-16
	 * update niujs 2015-3-16
	 * @param sourceFile
	 * @param flvFile void
	 */
	public static void convertWmvToFlv(String sourceFile, String flvFile) {
		String newFlvCLI = "";
		if(System.getProperty("os.name").indexOf("Windows")>-1){
			newFlvCLI = replaceCLI(
					flvCLI, 
					new String[] {"inputFile", "outputFile"}, 
					new String[] {sourceFile, flvFile}
			);
		} else {
			newFlvCLI = replaceCLI(
					wmvFlvLinux, 
					new String[] {"inputFile", "outputFile"}, 
					new String[] {sourceFile, flvFile}
			);
		}
		
		try {
			//Process process = Runtime.getRuntime().exec(newFlvCLI);
			Process process = null;
			try {
				process = Runtime.getRuntime().exec(newFlvCLI);
				
				new  StreamGobble(process.getInputStream(),  "INFO" ).start();   
			    new  StreamGobble(process.getErrorStream(),  "ERROR" ).start();   
			    int  status = process.waitFor();   
			    System.out.println("Process exitValue: "  + status);   
	        } catch (Throwable t) {   
				t.printStackTrace();   
	        } finally {   
		        if  (process ==  null )   
		            process.destroy();   
		        process = null ;   
		    } 
        } catch (Throwable t) {   
			t.printStackTrace();   
        }   
	}
	
	public static void catchVframesToGIF(String sourceFile, String videoFile) {
		String newFlvCLI = "";
		if(System.getProperty("os.name").indexOf("Windows")>-1){
			newFlvCLI = replaceCLI(
					gifCLI, 
					new String[] {"inputFile", "outputFile"}, 
					new String[] {sourceFile, videoFile}
			);
		}else{
			newFlvCLI = replaceCLI(
					gifLinux, 
					new String[] {"inputFile", "outputFile"}, 
					new String[] {sourceFile, videoFile}
			);
		}
		
		try {
			Process process = Runtime.getRuntime().exec(newFlvCLI);		    
			/*InputStream stderr = process.getErrorStream();   
            InputStreamReader isr = new InputStreamReader(stderr);   
            BufferedReader br = new BufferedReader(isr);   
            String line = null;   
            System.out.println("<ERROR>");   
            while ( (line = br.readLine()) != null)   
                System.out.println(line);   
            System.out.println("</ERROR>");   
            int exitVal = process.waitFor();   
            System.out.println("Process exitValue: " + exitVal);   */
        } catch (Throwable t) {   
			t.printStackTrace();   
        }   
	}
	
	public static void catchVideoJPG(String sourceFile, String videoFile,String width,String height) {
		String newFlvCLI = "";
		if(System.getProperty("os.name").indexOf("Windows")>-1){
			newFlvCLI = replaceCLI(
					jpgCLI, 
					new String[] {"inputFile", "outputFile","width","height"}, 
					new String[] {sourceFile, videoFile,width,height}
			);
		}else{
			newFlvCLI = replaceCLI(
					jpgLinux, 
					new String[] {"inputFile", "outputFile","width","height"}, 
					new String[] {sourceFile, videoFile,width,height}
			);
		}
		
		try {
			Process process = Runtime.getRuntime().exec(newFlvCLI);		    
			/*
			InputStream stderr = process.getErrorStream();   
            InputStreamReader isr = new InputStreamReader(stderr);   
            BufferedReader br = new BufferedReader(isr);   
            String line = null;   
            System.out.println("<ERROR>");   
            while ( (line = br.readLine()) != null)   
               System.out.println(line);   
            System.out.println("</ERROR>");   
            int exitVal = process.waitFor();   
            System.out.println("Process exitValue: " + exitVal);   */
        } catch (Throwable t) {   
			t.printStackTrace();   
        }   
    }   
	
	
	/*
	   * 替换命令行字符串 
	   * @param CLI String 原始命令行字符串  
	   * @param Type String[] 要替换的字符类型数组  
	   * @param File String[] 转换文件的相关数组  
	   * @return String 替换后的命令行字符串  
	*/  
	private static String replaceCLI(String CLI, String Type[], String File[]) {
		for (int i = 0; i < Type.length; i++)
			CLI =  replaceStr( (new StringBuilder()).append("%").append(Type[i]).append("%").toString(), File[i],CLI);
		return CLI;
	}
		

	/*
	   * 替换字符串 
	   * @param from String 原始字符串  
	   * @param to String 目标字符串  
	   * @param source String 母字符串  
	   * @return String 替换后的字符串  
	*/  
	public static String replaceStr(String from, String to, String source) {   
	    if (source == null || from == null || to == null)   
	    	return null;   
	    StringBuffer bf = new StringBuffer("");   
	    int index = -1;   
	    while ((index = source.indexOf(from)) != -1) {   
	    	bf.append(source.substring(0, index) + to);   
	    	source = source.substring(index + from.length());   
	    	index = source.indexOf(from);   
	    }   
	    bf.append(source);   
	    return bf.toString();   
	}   

	//test
	public static void main(String args[]){
		//convertVideoToFlv("F:\\视频\\视频测试\\电信纸飞机广告.avi", "D:\\res-41-201004261650438430.flv");
		//catchVframesToGIF("D:\\生产部2010年6月11日焊接比赛视频资料.mpg", "D:\\1.gif");
		//catchVideoJPG("D:\\生产部2010年6月11日焊接比赛视频资料.mpg", "D:\\1.jpg","160","120");		
	}

}
